package com.example.demo.leetcode.top100;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _42将有序数组转换为二叉搜索树
 * @description
 * @date 2023/06/15 22:36
 * <p>
 * ******************************************************
 */
public class _42将有序数组转换为二叉搜索树 {

    public TreeNode sortedArrayToBST(int[] nums) {
        int length = nums.length;
        return bst(nums, 0, length - 1);
    }

    private TreeNode bst(int[] nums, int left, int right) {
        if (right < left) {
            return null;
        }
        int mid = right - (right - left) / 2;
        TreeNode treeNode = new TreeNode(nums[mid]);
        treeNode.left = bst(nums, left, mid - 1);
        treeNode.right = bst(nums, mid + 1, right);
        return treeNode;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
